<!DOCTYPE html>
<%@page import="com.tdcy.biz.utils.CommonUtils"%>
<%@page import="com.tdcy.sys.util.BusiContextExt"%>
<%@page import="com.tdcy.sys.service.bean.LoginInfoBean"%>
<%@page import="com.tdcy.framework.util.StringUtils"%>
<%@page import="com.tdcy.sys.util.CodeTableUtils"%>
<%@page import="com.tdcy.framework.util.RequestUtils"%>
<%@page import="com.tdcy.sys.util.ParamUtils"%>
<%@page import="com.tdcy.framework.util.SessionUtils"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@ taglib tagdir="/WEB-INF/tags" prefix="biztag"%>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>配置管理中心</title>

	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<jsp:include page="../../hcommon.jsp"></jsp:include>
	<link rel="stylesheet" type="text/css" href="${path }/resource/js/ztree/css/ztree.css" />
	<link rel="stylesheet" type="text/css" href="${path }/resource/js/ztree/css/zTreeStyle.css" />
	<script src="${path }/resource/js/ztree/js/jquery.ztree.all-3.4.min.js" ></script>
	<script src="${path }/resource/js/ztree/js/jquery.ztree.exhide-3.4.min.js" ></script>
	<%
		String userkindjson = CodeTableUtils.getCodeBeanJson("user_kind");
		LoginInfoBean logininfobena = BusiContextExt.getLoginInfo();
	%>
<style type="text/css">
html, body{overflow: hidden; margin:0px;}
.text{width:95%}
#DivList{height:600px;overflow-x:hidden;overflow-y:hidden;text-align:left;white-space:nowrap}
#divMenuTree{height:600px;overflow-x:hidden;overflow-y:scroll;text-align:left;white-space:nowrap}
</style>


<body class="gray-bg skin-1">
	<div class="wrapper wrapper-content animated fadeInRight">
		<div class="row">
			<div class="col-sm-12">
				<div class="ibox float-e-margins">
					<div class="ibox-title">
						<h5>
						角色管理</h5>
					</div>
					<div class="ibox-content">
					    <div>
					    	<div class="row">
								<div class="col-sm-4 col-md-4" >
									<div class="jqGrid_wrapper uadmin-grid-margin" >
								        <table id="queryGrid">
								        </table>
								        <div id="pager_queryGrid"></div>
									</div>
								</div>
								<div class="col-sm-8 col-md-8" >
									<div class="row">
									  <div class="col-sm-6 col-md-6" >
										<div class="jqGrid_wrapper uadmin-grid-margin" >
									        <form  id="roleform"  class="form-horizontal" >  
										       <div class="form-group">   
										         <label class="col-sm-4 control-label">角色名称：</label> 
										        <div class="col-sm-8">  
										            <input class="form-control" name="roleName"  id="roleName"  datatype="*" nullmsg="不能为空"/>
										             <div class="Validform_checktip"></div>
										       </div>  
										       </div>   
										       <div class="form-group">   
										        <label for="lastname" class="col-sm-4 control-label">角色代码：</label>   
										        <div class="col-sm-8">  
										         <input class="form-control" name="roleCode"  id="roleCode" />
										         </div>  
										       </div> 
										        <div class="form-group">   
										        <label for="lastname" class="col-sm-4 control-label">角色类型：</label>   
										        <div class="col-sm-8">  
										       		 <biztag:Comp-CodeRadio name="userKind" code="user_kind"/>
										         </div>  
										       </div> 
										       <div class="form-group">   
										         <label for="roleDesc" class="col-sm-4 control-label">部门描述：</label>
										        <div class="col-sm-8">  
										           <textarea class="form-control" name="roleDesc"  id="roleDesc" cols="35" rows="3"></textarea>
										         </div>  
										       </div> 
										     </form> 
										</div>
									</div>
									<div  class="col-sm-6 col-md-6">
										<div id="divMenuTree" style="border:  1px solid #F5FAFC;width: 580px;">
			                                <ul id="tvMenu" class="ztree" >
			                                </ul>
			                            </div>
									</div>
								</div>
								<div class="row">
								  <div style="text-align: center;margin-top: 2px;margin-bottom: 2px;">
										<button class="btn btn-sm btn btn-sm btn-primary" onclick="javascript:doAdd();" ><span>新增</span></button>
										<button class="btn btn-sm btn btn-sm btn-info"  onclick="javascript:doSave();" ><span>保存</span></button>
										<button class="btn btn-sm btn btn-sm btn-danger" onclick="javascript:doDel();" ><span>删除</span></button>
									</div>
									</div>
								</div>
								
							</div>
						</div>
					</div>	
				</div>
			</div>
		</div>
	</div>
</body>

<script type="text/javascript">
	var appName = "${appName}";
	var userkindjson =  <%=userkindjson%>;
	var curRoleId;
	var _menuTree;
	var curRoleInfo ;
	var curMenuInfo;
	
	var NEWID = "-100";
	var rootId = "0";
	var allRoleData = null;
	
	var formValid = null;
	$(document).ready(function() {
		formValid = AppKit.formTipValidate("roleform");
		
		initQueryGrid();
		
		getMenuTree();
	});
	
	function initQueryGrid() {
		var queryParams = {};
		var colModel=[];
	   var col1={label: '用户类型', name: '', align: 'center',width: 120,sortable:true, formatter:userKindFormatter};
	      colModel.push(col1);
	   var col2={label: '角色名称', name: 'roleName', align: 'center',width: 120,sortable:true,};
	      colModel.push(col2);
      var col2={label: '角色代码', name: 'roleCode', align: 'center',width: 120,sortable:true,};
      colModel.push(col2);
      var col2={label: '描述', name: 'roleDesc', align: 'center',width: 120,sortable:true,};
      colModel.push(col2);
	   var col5={label: 'roleId', name: 'roleId', align: 'center',width: 200,sortable:true,hidden:true};
	      colModel.push(col5);
	      var col5={label: 'userKind', name: 'userKind', align: 'center',width: 200,sortable:true,hidden:true};
	      colModel.push(col5);
	        
		var settings={
	       postData: queryParams,
	       styleUI : 'Bootstrap',
		    mtype: "post",
		    url: "${path}/sys/getallrole",
		    prmNames:{//请求参数格式预处理
		          page:"page",
		          rows:"rows", 
		          sort:"sort",
		          order: "order"
		    },
	       datatype: "json",
	       colModel:colModel,
	       pageable: false,
		    page: 1,
	       rowNum: '-1',
	       multiSort: true,
		    sortable: true,
		    sortname: "id",
		    sortorder: "asc",
		    multiselect: false,
		    shrinkToFit: true,
		    height: 550,
		    shrinkToFit: true,
		   
		    jsonReader: {//返回参数格式处理
		        root: "data"
		    },
		    rownumbers: false,
		    multikey: "true",
		    autowidth: true,
		    onSelectRow:onRoleClick
	      };
	      $("#queryGrid").jqGrid(settings);
	  };
	  
	function getMenuTree(){
		var url ="${path}/sys/getallmenuAndright";
		AppKit.postJSON(url, null, showMenuTree);
	}
	
	function showMenuTree(json){
		if (!AppKit.checkJSONResult(json)) {
            return;
        }
		buildMenuTree(json.data);
	}
	
	function buildMenuTree(menuList){
	   try{
	        var treedata = new Array();
        	var rootmenu = {"id":"0","pId":"","name":appName,"data":"", open:true, "iconSkin":"system"};
            treedata.push(rootmenu);
	        
	    	for(var i in menuList){
	    		var j = menuList[i];
	    		
	    		var tree = {};
	    		
	    		if(j.menuId == "1"){
	    			 tree = {"id":j.menuId,"pId":j.menuUpId,"name":j.menuName,"data":j.menuUrl, open:true, "iconSkin":"system"};
	    		}else{
	    			 tree = {"id":j.menuId,"pId":j.menuUpId,"name":j.menuName,"data":j.menuUrl,"iconSkin":"menu"};
	    		}
	    		treedata.push(tree);
	    	}
	    	
	        
	        var setting = {
	    			view: {
	    				fontCss: getTreeFont,
	    				autoCancelSelected: false,
						selectedMulti: false,
						dblClickExpand: false,
						showLine: false
	    			},
	    			data: {
	    				simpleData: {
	    					enable: true,
	    					rootPId: rootId
	    				}
	    			},
					callback: {
						onClick: onTreeClick
					},
					check: {
						enable: true,
						chkStyle: "checkbox" ,
						chkboxType: {"Y": "ps", "N": "s"},
						autoCheckTrigger: false
					}
	    	};
	        
	        $.fn.zTree.init($("#tvMenu"), setting, treedata);
	        treedata.length = 0;
	        
	        _menuTree = $.fn.zTree.getZTreeObj("tvMenu");
	        
	        setEmptyRole();
	        curRoleId = NEWID;
	    } catch(e){
	    	alert(e.message);
	    }
	}
	
	function getTreeFont(treeId, node) {
    	return (!!node.highlight) ? {"background-color":"#ffff96"} : (node.font ? node.font : {"background-color":"transparent"});
    }
	
	function onTreeClick(event, treeId, treeNode, clickFlag) {
    	if(_menuTree){
    		_menuTree.expandNode(treeNode);	
    	}
	}
	
	 function getSelectMenu(){
	    	var a=[];
			var nodes = _menuTree.getCheckedNodes(true);
			for(var idx in nodes){
				a.push(nodes[idx].id);
			}
			
	        var str = a.join(",");
	        a.length = 0;
	        return str;
		}

	function onRoleClick(id) {
		 var rowData = $("#queryGrid").jqGrid('getRowData',id);
		 console.log(rowData);
		if (rowData && rowData.roleName) {
			if(curRoleId == rowData.roleId){
				return;
			}
			curRoleId = rowData.roleId;

			$("#roleform #roleName").val(rowData.roleName);
			$("#roleform #roleCode").val(rowData.roleCode);
			$("#roleform #disOrder").val(rowData.disOrder);
			
			AppKit.setRadioValues("userKind", rowData["userKind"]);
			
			if(rowData["isDelete"] == "1"){
				$("#ttinfo").html("内置角色不能更新、删除");
				$("#roleform #roleName").attr("readonly",true);
				$("#roleform #roleCode").attr("readonly",true);
				$("#roleform #roleDesc").attr("readonly",true);
				
				$("input[name='userKind']").attr("disabled",true);
			}else{
				$("#ttinfo").html("");
				$("#roleform #roleName").attr("readonly",false);
				$("#roleform #roleCode").attr("readonly",false);
				$("#roleform #roleDesc").attr("readonly",false);
				$("input[name='userKind']").attr("disabled",false);
			}

			_menuTree.checkAllNodes(false);	
		    var url ="${path}/sys/getrolemenuAndright";
			AppKit.postJSON(url, {"roleId": curRoleId }, showRoleMenu);
		}
	}
	
	function showRoleMenu(json){
		if (!AppKit.checkJSONResult(json)) {
            return;
        }
		
		 var menus = json.data;
		 //alert(AppKit.tostring(menus));
         if (AppKit.isarray(menus)) {
        	 if(menus.length>0){
                 for (var idx in menus) {
     	            var menuId = menus[idx].menuId;
                   	if(menuId){
                   		var node = _menuTree.getNodeByParam("id",menuId);
                   		if(node){
                   			node.checked = true;
                   			_menuTree.updateNode(node, false);
                   		}
                   	}
                 }
        	 }else{
     	    	_menuTree.checkAllNodes(false);	
        	 }
         }
         
	}
	

	function doSave() {
		var flag = formValid.check();
		if(!flag){
			return;
		}
		
		var roleinfo = $("#roleform").serializeObject();
		var menuinfo = getSelectMenu();
		if(roleinfo == curRoleInfo && menuinfo == curMenuInfo){
			AppKit.showTipMessage("没有修改不要保存");
			return;
		}
		
		if(AppKit.isEmptyVal(roleinfo.roleName)){
			AppKit.showTipMessage("角色名称不能为空");
			return;
		}
		
		var url = "";
		if(curRoleId == NEWID){
			url ="${path}/sys/addrole";
		}else{
			url ="${path}/sys/updaterole";
		}
		
		roleinfo["rights"] = menuinfo;
		roleinfo["roleId"] = curRoleId;
		//alert(AppKit.tostring(roleinfo));
		AppKit.postJSON(url,roleinfo, saveSuccess);
	}
	
    function saveSuccess(json){
	    if(!AppKit.checkJSONResult(json)){
		    return;
	    }
	    AppKit.showTipMessage(json.message);
	    reloadTable();
    }
	
	function setCurRoleInfo(){
		curRoleInfo =  $("#roleform").serializeObject();
		curMenuInfo = getSelectMenu();
	}

	function doAdd() {
		_menuTree.checkAllNodes(false);	
		setEmptyRole();
		
		curRoleId = NEWID;
	}

	function doDel() {
		var id=$('#queryGrid').jqGrid('getGridParam','selrow');
		var rowData = $('#queryGrid').jqGrid('getRowData',id);
		if (rowData && rowData.roleId) {
			if(rowData.roleId == "1"){
				AppKit.showTipMessage("不能删除系统管理员角色");
				return;
			}
			
			AppKit.showConfirmMessage(function() {
				 var url ="${path}/sys/delrole";
					AppKit.postJSON(url, {"roleId": rowData.roleId }, delSuccess);
			});
		}else{
			AppKit.showTipMessage("请选择要删除的记录");
		}
	}
	
    function delSuccess(json){
	    if(!AppKit.checkJSONResult(json)){
		    return;
	    }
	    
	    reloadTable();
	    setEmptyRole();
	    curRoleId = NEWID;
	   	AppKit.showTipMessage(json.message);
    }
    
    function reloadTable(){
		$("#queryGrid").trigger("reloadGrid"); //重新载入    
	}
    
    function setEmptyRole(){
    	 _menuTree.checkAllNodes(false);
 		 $("#roleform #roleName").val("");
 		 $("#roleform #roleDesc").val("");
 		 $("#roleform #roleCode").val("");
    }
    
    function userKindFormatter(val, options, rec){
       return AppKit.getCodeFormatter(rec.userKind, rec, userkindjson);
  }
</script>

</html>